const TOAST_PREFAB = "prefabs/ui/Toast";   //Toast的prefab动态加载路径
let _instanceNode;
let instance;
let Toast = cc.Class({
  extends: cc.Component,
  
  properties: {
    label: cc.Label,
    showDuration: 2,
    paddingLeft: 50,
    paddingRight: 50,
    paddingTop: 20,
    paddingBottom: 20,
  },
  onLoad() {
    this.node.active = false;
  },
  
  updatePadding() {
    this.scheduleOnce(() => {
      let labelSize = this.label.node.getContentSize();
      this.node.width = labelSize.width + this.paddingLeft + this.paddingRight;
      this.node.height = labelSize.height + this.paddingTop + this.paddingBottom;
    }, 0);
    
  }
  
});

Toast.init = function (callback) {
  if (!instance) {
    cc.loader.loadRes(TOAST_PREFAB, cc.Prefab, function (err, prefab) {
      _instanceNode = cc.instantiate(prefab);
      _instanceNode.parent = cc.director.getScene();
      instance = _instanceNode.getComponent(Toast);
      cc.game.addPersistRootNode(_instanceNode);
      if (callback) {
        callback();
      }
    });
  }
};

function _doShow(message, duration, fade, callback) {
  instance.label.string = message;
  instance.updatePadding();
  instance.node.stopAllActions();
  instance.node.active = true;
  instance.node.opacity = 0;
  if (duration === undefined) {
    duration = instance.showDuration;
  }
  instance.node.zIndex = cc.macro.MAX_ZINDEX;
  if (fade === undefined) {
    fade = 0.2;
  }
  instance.node.runAction(cc.sequence(
    cc.fadeIn(fade),
    cc.delayTime(duration),
    cc.fadeOut(fade),
    cc.callFunc(() => {
      instance.node.active = false;
      if (callback) {
        callback();
      }
    })
  ));
}


Toast.show = function (message, duration, fade, callback) {
  if (instance) {
    _doShow(message, duration, fade, callback);
  } else {
    Toast.init(() => {
      _doShow(message, duration, fade, callback);
    })
  }
};
module.exports = Toast;